import React, { useState, useEffect } from 'react';
import './qjx_gou.css';
import { LeftOutline } from 'antd-mobile-icons';
import { useNavigate } from "react-router-dom";

// 初始商品数据
const initialProducts = [
    {
        id: 1,
        name: '乐心手环5S 标准版',
        price: 149,
        quantity: 4
    },
    {
        id: 2,
        name: '乐心手环5S 标准版',
        price: 149,
        quantity: 1
    },
    {
        id: 3,
        name: '乐心手环5S 标准版',
        price: 149,
        quantity: 1
    },
    {
        id: 4,
        name: '乐心手环5S 标准版',
        price: 149,
        quantity: 1
    }
];

const App = () => {
    // 存储商品列表，使用状态管理
    const [products, setProducts] = useState(initialProducts);
    // 存储选中商品的 ID
    const [selectedProducts, setSelectedProducts] = useState([]);
    // 存储总金额
    const [totalPrice, setTotalPrice] = useState(0);

    // 处理商品数量的增减
    const handleQuantityChange = (productId, change) => {
        setProducts(prevProducts =>
            prevProducts.map(product => {
                if (product.id === productId) {
                    // 确保数量不小于 1
                    return {
                        ...product,
                        quantity: Math.max(1, product.quantity + change)
                    };
                }
                return product;
            })
        );
    };

    // 处理复选框的选中和取消选中
    const handleCheckboxChange = (productId, isChecked) => {
        if (isChecked) {
            setSelectedProducts(prevSelected => [...prevSelected, productId]);
        } else {
            setSelectedProducts(prevSelected => prevSelected.filter(id => id!== productId));
        }
    };

    // 计算总金额
    const calculateTotalPrice = () => {
        let total = 0;
        selectedProducts.forEach(id => {
            const product = products.find(p => p.id === id);
            if (product) {
                total += product.price * product.quantity;
            }
        });
        setTotalPrice(total);
    };

    // 处理全选操作
    const handleSelectAll = () => {
        if (selectedProducts.length === products.length) {
            setSelectedProducts([]);
        } else {
            const allIds = products.map(p => p.id);
            setSelectedProducts(allIds);
        }
    };

    // 使用 useEffect 监听 selectedProducts 和 products 的变化，重新计算总金额
    useEffect(() => {
        calculateTotalPrice();
    }, [selectedProducts, products]);
const navigate = useNavigate();
    return (
        <div>
            {/* 渲染商品列表 */}
            <div className='y_one'>
        <p style={{ marginTop: '3px' }} onClick={() => navigate('/home/mind')}>
          <LeftOutline fontSize={24} />
        </p>
        <h2>购 物 车</h2>
      </div>
            {products.map(product => (
                <div key={product.id} className="gou_product-item">
                    <input
                        type="checkbox"
                        onChange={(e) => handleCheckboxChange(product.id, e.target.checked)}
                        checked={selectedProducts.includes(product.id)}
                    />
                    <img src="123.png" alt={product.name} />
                    <div>{product.name}</div>
                    <div>￥{product.price}</div>
                    <div className="gou_quantity-buttons">
                        <button onClick={() => handleQuantityChange(product.id, -1)}>-</button>
                        <span>{product.quantity}</span>
                        <button onClick={() => handleQuantityChange(product.id, 1)}>+</button>
                    </div>
                </div>
            ))}
            {/* 底部结算栏 */}
            <div className="gou_checkout-bar">
                <input
                    type="checkbox"
                    onChange={handleSelectAll}
                    checked={selectedProducts.length === products.length}
                />全选
                {selectedProducts.length > 0 && (
                    <>
                        <div>合计：￥{totalPrice}</div>
                        <button>去结算({selectedProducts.length})</button>
                    </>
                )}
            </div>
        </div>
    );
};

export default App;